package com.linkage.bookshop.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.linkage.bookshop.authentication.CrendentialSessionService;
import com.linkage.bookshop.model.Book;
import com.linkage.bookshop.model.Order;
import com.linkage.bookshop.model.Orderline;
import com.linkage.bookshop.model.Trolleyline;
import com.linkage.bookshop.repository.OrderRepository;
import com.linkage.bookshop.service.inter.BookService;
import com.linkage.bookshop.service.inter.CommentService;
import com.linkage.bookshop.service.inter.OrderService;
import com.linkage.bookshop.service.inter.TrolleyService;

@Controller
@RequestMapping("/order/*")
public class OrderController {
	@Autowired
	private OrderRepository orderRepository;
	@Autowired
	private OrderService orderService;
	@Autowired
	private BookService bookService;
	@Autowired
	private TrolleyService trolleyService;
	@Autowired
	private CommentService commentService;
	@Resource
	private CrendentialSessionService crendentialSessionService;

	@RequestMapping(value = "/directPurchase", method = RequestMethod.GET)
	public String directPurchase(Model model,
			@RequestParam("bookId") int bookId,
			@RequestParam("quantity") int orderlineAmount) {
		int storageVolume = bookService.loadBookDetail(bookId)
				.getStorageVolume();
		if (storageVolume < orderlineAmount) {
			model.addAttribute("error", "库存量不足,请重新购买");
			return "order/error";
		}
		String bookName = bookService.loadBookDetail(bookId).getName();
		model.addAttribute("bookId", bookId);
		model.addAttribute("bookName", bookName);
		model.addAttribute("orderlineAmount", orderlineAmount);
		return "order/receive_info";
	}

	@RequestMapping(value = "/joinTrolley", produces = "application/json", method = RequestMethod.GET)
	@ResponseBody
	public Map<String, Object> joinTrolley(HttpServletRequest request,
			HttpServletResponse response, @RequestParam("bookId") int bookId,
			@RequestParam("quantity") int orderlineAmount) {
		Map<String, Object> params = new HashMap<>();
		String username = crendentialSessionService.getUsername(request);
		Cookie[] cookies = request.getCookies();
		Cookie cookie = trolleyService.joinTrolley(cookies, username, bookId,
				orderlineAmount);
		cookie.setMaxAge(3600);
		response.addCookie(cookie);
		/*
		 * String url="redirect:/order/checkTrolley"; return url;
		 */
		params.put("result", true);
		return params;

	}

	@RequestMapping(value = "/checkTrolley")
	public String checkTrolley(Model model, HttpServletRequest request) {
		String username = crendentialSessionService.getUsername(request);
		Cookie[] cookies = request.getCookies();
		List<Trolleyline> tls = trolleyService.checkTrolley(cookies, username);
		if (tls == null) {
			return "order/null";
		}
		model.addAttribute("tls", tls);
		return "order/trolley";
	}

	@RequestMapping(value = "/submitOrder", method = RequestMethod.GET)
	public String submitOrder(Model model, HttpServletRequest request,
			@RequestParam("bookId") int bookId,
			@RequestParam("orderlineAmount") int orderlineAmount,
			@RequestParam("receiverName") String receiverName,
			@RequestParam("receiverAddr") String receiverAddr,
			@RequestParam("receiverPhonenum") String receiverPhonenum,
			@RequestParam("note") String note) {
		String username = crendentialSessionService.getUsername(request);
		String receiverInfo = "receiver_name:" + receiverName
				+ ",receiver_addr:" + receiverAddr + ",receiver_phonenum:"
				+ receiverPhonenum + ",note:" + note;
		int orderId = orderService.submitOrder(bookId, orderlineAmount,
				username, receiverInfo);
		boolean b = true;
		bookService.modifyVolume(bookId, orderlineAmount, b);
		Order order = orderRepository.selectOrderById(orderId);
		Book book = bookService.loadBookDetail(bookId);
		model.addAttribute("orderId", orderId);
		model.addAttribute("bookName", book.getName());
		model.addAttribute("bookPrice", book.getOutPrice());
		model.addAttribute("orderlineAmount", orderlineAmount);
		model.addAttribute("price", order.getPrice());
		model.addAttribute("receiverName", receiverName);
		model.addAttribute("receiverAddr", receiverAddr);
		model.addAttribute("receiverPhonenum", receiverPhonenum);
		model.addAttribute("note", note);
		return "order/pay";
	}

	@RequestMapping(value = "/pay", method = RequestMethod.GET)
	public String pay(Model model, HttpServletRequest request,
			@RequestParam("orderId") int orderId,
			@RequestParam("price") double price) {
		String username = crendentialSessionService.getUsername(request);
		boolean b = orderService.pay(price, username);
		if (b) {
			orderService.changeOrderStatus(3, orderId);
			return "order/paySuccess";
		}
		model.addAttribute("error", "财富不够,请重新购买");
		return "order/error";
	}

	// 查看自己的订单
	@RequestMapping(value = "/myOrders", method = RequestMethod.GET)
	public String myOrder(Model model, HttpServletRequest request) {
		String username = crendentialSessionService.getUsername(request);
		List<Order> orders = orderService.listOrders(username);
		model.addAttribute("orders", orders);
		return "order/myOrders";
	}

	// 查看订单信息
	@RequestMapping(value = "/viewOrderDetails", method = RequestMethod.GET)
	public String viewOrderDetails(Model model,
			@RequestParam("orderId") int orderId,
			@RequestParam("status") int status) {
		List<Orderline> ols = orderService.checkOrderline(orderId);
		model.addAttribute("ols", ols);
		model.addAttribute("status", status);
		return "order/viewOrderDetails";
	}

	// 确认收货
	@RequestMapping(value = "/commitOrder", method = RequestMethod.GET)
	public String commitOrder(Model model, @RequestParam("orderId") int orderId) {
		orderService.changeOrderStatus(5, orderId);
		String url = "redirect:/order/myOrders";
		return url;
	}

	// 发表评论
	@RequestMapping(value = "/addComment", method = RequestMethod.GET)
	public String addComment(Model model, @RequestParam("bookId") int bookId,
			@RequestParam("orderlineId") int orderlineId) {
		model.addAttribute("bookId", bookId);
		model.addAttribute("orderlineId", orderlineId);
		return "order/addComment";
	}

	// 提交评论
	@RequestMapping(value = "/submitComment", method = RequestMethod.GET)
	public String submitComment(HttpServletRequest request,
			@RequestParam("bookId") int bookId,
			@RequestParam("grade") int grade,
			@RequestParam("content") String content,
			@RequestParam("orderlineId") int orderlineId) {
		String username = crendentialSessionService.getUsername(request);
		commentService.insert(username, bookId, content, grade);
		orderService.changeCommentFlag(orderlineId);
		return "order/commentSuccess";
	}

	// 购物车购买
	@RequestMapping(value = "/trolleyBuy", method = RequestMethod.GET)
	public String trolleyBuy() {
		return "order/receive_info_t";
	}

	// 购物车提交订单
	@RequestMapping(value = "/submitTrolley", method = RequestMethod.GET)
	public String submitTrolley(Model model, HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam("receiverName") String receiverName,
			@RequestParam("receiverAddr") String receiverAddr,
			@RequestParam("receiverPhonenum") String receiverPhonenum,
			@RequestParam("note") String note) {
		String receiverInfo = "receiver_name:" + receiverName
				+ ",receiver_addr:" + receiverAddr + ",receiver_phonenum:"
				+ receiverPhonenum + ",note:" + note;
		String username = crendentialSessionService.getUsername(request);
		Cookie[] cookies = request.getCookies();
		List<Trolleyline> tls = trolleyService.checkTrolley(cookies, username);
		int orderId = orderService.submitOrder(tls, receiverInfo, username);
		Order order = orderRepository.selectOrderById(orderId);
		Cookie cookie = trolleyService.removeCookie(username, cookies);
		response.addCookie(cookie);
		double price = order.getPrice();
		model.addAttribute("orderId", orderId);
		model.addAttribute("tls", tls);
		model.addAttribute("price", price);
		model.addAttribute("receiverName", receiverName);
		model.addAttribute("receiverAddr", receiverAddr);
		model.addAttribute("receiverPhonenum", receiverPhonenum);
		model.addAttribute("note", note);
		return "order/pay_t";
	}

	// 购物车单独购买
	@RequestMapping(value = "/trolleyPurchase", method = RequestMethod.GET)
	public String trolleyPurchase(Model model,
			@RequestParam("bookId") int bookId,
			@RequestParam("quantity") int orderlineAmount) {
		int storageVolume = bookService.loadBookDetail(bookId)
				.getStorageVolume();
		if (storageVolume < orderlineAmount) {
			model.addAttribute("error", "库存量不足,请重新购买");
			return "order/error";
		}
		String bookName = bookService.loadBookDetail(bookId).getName();
		model.addAttribute("bookId", bookId);
		model.addAttribute("bookName", bookName);
		model.addAttribute("orderlineAmount", orderlineAmount);
		return "order/receive_info_only";
	}

	// 购物车单独提交订单
	@RequestMapping(value = "/submitOrderT", method = RequestMethod.GET)
	public String submitOrderT(Model model, HttpServletRequest request,
			HttpServletResponse response, @RequestParam("bookId") int bookId,
			@RequestParam("orderlineAmount") int orderlineAmount,
			@RequestParam("receiverName") String receiverName,
			@RequestParam("receiverAddr") String receiverAddr,
			@RequestParam("receiverPhonenum") String receiverPhonenum,
			@RequestParam("note") String note) {
		String username = crendentialSessionService.getUsername(request);
		String receiverInfo = "receiver_name:" + receiverName
				+ ",receiver_addr:" + receiverAddr + ",receiver_phonenum:"
				+ receiverPhonenum + ",note:" + note;
		int orderId = orderService.submitOrder(bookId, orderlineAmount,
				username, receiverInfo);
		boolean b = true;
		bookService.modifyVolume(bookId, orderlineAmount, b);
		Cookie cookie = trolleyService.removeFromTrolley(request.getCookies(),
				username, bookId, orderlineAmount);
		response.addCookie(cookie);
		Order order = orderRepository.selectOrderById(orderId);
		Book book = bookService.loadBookDetail(bookId);
		model.addAttribute("orderId", orderId);
		model.addAttribute("bookName", book.getName());
		model.addAttribute("bookPrice", book.getOutPrice());
		model.addAttribute("orderlineAmount", orderlineAmount);
		model.addAttribute("price", order.getPrice());
		model.addAttribute("receiverName", receiverName);
		model.addAttribute("receiverAddr", receiverAddr);
		model.addAttribute("receiverPhonenum", receiverPhonenum);
		model.addAttribute("note", note);
		return "order/pay";
	}

	// 购物车删除单行
	@RequestMapping(value = "/trolleyRemove", method = RequestMethod.GET)
	public String trolleyRemove(HttpServletRequest request,
			HttpServletResponse response, @RequestParam("bookId") int bookId,
			@RequestParam("quantity") int orderlineAmount) {
		String username = crendentialSessionService.getUsername(request);
		Cookie cookie = trolleyService.removeFromTrolley(request.getCookies(),
				username, bookId, orderlineAmount);
		response.addCookie(cookie);
		return "redirect:/order/checkTrolley";
	}

	@RequestMapping(value = "/listOrders", method = RequestMethod.GET)
	public String listOrders(Model model) {
		orderService.listAllOrders(3);
		List<Order> orders = orderService.listAllOrders(3);
		model.addAttribute("orders", orders);

		return "order/orders";
	}

	@RequestMapping(value = "order/orderDeal", method = RequestMethod.GET)
	public String orderDeal(Model model, @RequestParam("id") int id) {
		orderService.changeOrderStatus(4, id);
		return "redirect:listOrders";
	}

	@RequestMapping(value = "/manageOrder", produces = "application/json", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> manageOrder() {
		Map<String, Object> params = new HashMap<>();
		params.put("result", true);
		return params;
	}
}